package com.llxz.blog.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.StringUtils;


import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author zzh
 * @description: date: 2021/9/3 14:20
 */


public class JwtUtils {
    //常量
    public static final long EXPIRE_TIME = 1000 * 60 * 60 * 24;//token过期时间
    public static final String TOKEN_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";//秘钥

    //获取加密后的token
    public static String createJwtToken(String id, String name){
        //过期时间和加密算法设置
        Date currentTime = new Date();
        Date  endTime = new Date(System.currentTimeMillis()+EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);

        //头部信息
        Map<String,Object> header = new HashMap<>(2);
        header.put("typ","JWT");
        header.put("alg","HS256");

        return JWT.create()
                .withIssuer("MP")
                .withAudience("blog")
                .withHeader(header)
                .withClaim("id",id)
                .withClaim("name",name)
                .withIssuedAt(currentTime)
                .withExpiresAt(endTime)
                .sign(algorithm);
    }

    public static boolean checkToken(String jwtToken){
        if (StringUtils.isEmpty(jwtToken))
            return false;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))
                    .withIssuer("MP")
                    .withAudience("blog")
                    .build();
            verifier.verify(jwtToken);
            return true;
        } catch (JWTVerificationException e){
            e.printStackTrace();
            return false;
        }
    }

    //请求头获取数据
    public static String getData(HttpServletRequest request){
        String jwtToken = request.getHeader("token");

        DecodedJWT jwt = JWT.decode(jwtToken);

        String id = jwt.getClaim("id").asString();

        return id;
    }

    public static String getData(String token){
        DecodedJWT jwt = JWT.decode(token);

        String id = jwt.getClaim("id").asString();
        System.out.println(id);

        return id;
    }
}